package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.TimeStrVo;
import com.ruoyi.system.service.*;
import com.ruoyi.system.util.BusinessException;
import com.ruoyi.system.util.RequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SysYongyouServiceImpl implements ISysYongyouService {

    private static final Logger logger = LoggerFactory.getLogger(SysYongyouServiceImpl.class);

    private static String appKey = "6cf1a34e0f0448288378ee95896ef105";
    private static String appSecret = "4213831e56b5491a8681911d19985056";
    private static String tenantId = "iku4yass";
    private static final String ALGORITHM = "HmacSHA256";

    @Autowired
    private ISysYongyouCgddService cgddService;

    @Autowired
    private ISysYongyouCgfpService cgfpService;

    @Autowired
    private ISysYongyouCgrkService cgrkService;

    @Autowired
    private ISysYongyouClckService clckService;

    @Autowired
    private ISysYongyouCprkService cprkService;

    @Autowired
    private ISysYongyouQtckService qtckService;

    @Autowired
    private ISysYongyouXsckService xsckService;

    @Autowired
    private ISysYongyouXsfpService xsfpService;

    @Autowired
    private ISysYongyouXshtService xshtService;

    @Override
    public int asyncXsht(TimeStrVo vo){
        String apiUrl = "/yonbip/sd/voucherorder/list";
        String accessUrl = getApiUrl(apiUrl);
        HashMap param = new HashMap();
        param.put("pageIndex", 1);
        param.put("pageSize", 500);

        String startTime = "2024-11-01 00:00:00";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String endTime = sdf.format(new Date())+" 23:59:59";
        param.put("open_vouchdate_begin", startTime);
        param.put("open_vouchdate_end", endTime);
//        List<HashMap<String,Object>> fieldsList = new ArrayList<>();
//        HashMap fields = new HashMap();
//        fields.put("field", "open_vouchdate_begin");
//        fields.put("op", "between");
//        fields.put("value1", startTime);
//        fields.put("value2", endTime);
//        fields.put("op", "like");
//        fields.put("value1", vo.getAsyncTimeStart());
//        fieldsList.add(fields);
//        param.put("simpleVOs", fieldsList);
        String result = null;
        try {
            result = RequestUtil.doPost(accessUrl, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject res = JSONObject.parseObject(result);
        JSONObject data = JSONObject.parseObject(res.getString("data"));
        int pageCount = data.getInteger("pageCount");
        int recordCount = data.getInteger("recordCount");
        logger.info("------recordCount-----" + recordCount);
        logger.info("------pageCount-----" + pageCount);
        if(pageCount>0) {
            xshtService.deleteByDateRange(startTime,endTime);
            for (int i = 1; i <= pageCount; i++) {
                Map sub = new LinkedHashMap<>();
                sub.put("pageIndex", i);
                sub.put("pageSize", 500);
                sub.put("open_vouchdate_begin", startTime);
                sub.put("open_vouchdate_end", endTime);
//                List<HashMap<String,Object>> SubFieldsList = new ArrayList<>();
//                HashMap subFields = new HashMap();
//                subFields.put("field", "vouchdate");
//                subFields.put("op", "between");
//                subFields.put("value1", startTime);
//                subFields.put("value2", endTime);
////                subFields.put("op", "like");
////                subFields.put("value1", vo.getAsyncTimeStart());
//                SubFieldsList.add(fields);
//                sub.put("simpleVOs", SubFieldsList);
                String subResult = null;
                try {
                    subResult = RequestUtil.doPost(accessUrl, sub);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                JSONObject subRes = JSONObject.parseObject(subResult);
                JSONObject subData = JSONObject.parseObject(subRes.getString("data"));
                JSONArray recordList = subData.getJSONArray("recordList");
                if (recordList.size() > 0) {
                    for (int index = 0; index < recordList.size(); index++) {
                        JSONObject record = recordList.getJSONObject(index);
                        SysYongyouXsht xsht = new SysYongyouXsht();
                        if(record.getString("pubuts")!=null) {
                            xsht.setSaledepartmentidName(record.getString("saleDepartmentId_name"));
                            xsht.setBizid(record.getString("orderDetailId"));
                            xsht.setCorpcontactusername(record.getString("corpContactUserName"));
                            xsht.setPubuts(record.getString("pubuts"));
                            xsht.setReceiver(record.getString("receiver"));
                            if(record.getString("oriSum")!=null) {
                                xsht.setOrisum(record.getBigDecimal("oriSum"));
                            }
                            xsht.setSettlementorgidName(record.getString("settlementOrgId_name"));
                            xsht.setSubqty(record.getBigDecimal("subQty"));
                            xsht.setQtyname(record.getString("qtyName"));
                            xsht.setOritaxunitprice(record.getString("oriTaxUnitPrice"));
                            xsht.setConsigntime(record.getString("consignTime"));
                            xsht.setRealproductcode(record.getString("realProductCode"));
                            xsht.setSkuname(record.getString("productName"));
                            xsht.setLinememo(record.getString("lineMemo"));
                            xsht.setOrderproducttype(record.getString("orderProductType"));
                            xsht.setPaystatuscode(record.getString("payStatusCode"));
                            xsht.setStatuscode(record.getString("statusCode"));
                            xsht.setNextstatus(record.getString("nextStatus"));
                            xsht.setReceivecontacterphone(record.getString("receiveContacterPhone"));
                            xsht.setProdefine1(record.getString("prodefine1"));
                            xsht.setSettlementName(record.getString("settlement_name"));
                            xsht.setTransactiontypeidName(record.getString("transactionTypeId_name"));
                            xsht.setAuditor(record.getString("auditor"));
                            xsht.setCreatetime(record.getString("createTime"));
                            xsht.setOrderdetailsFirstupcode(record.getString("orderDetails_firstupcode"));
                            xsht.setAgentidName(record.getString("agentId_name"));
                            if(record.getString("confirmPrice")!=null) {
                                xsht.setConfirmprice(record.getBigDecimal("confirmPrice"));
                            }
                            if(record.getString("payStatusCode")!=null) {
                                String payStatus = "";
                                if(record.getString("payStatusCode").equals("CONFIRMPAYMENT")) {
                                    payStatus = "部分付款待确认";
                                }else if(record.getString("payStatusCode").equals("NOTPAYMENT")) {
                                    payStatus = "未付款";
                                }else if(record.getString("payStatusCode").equals("CONFIRMPAYMENT_ALL")) {
                                    payStatus = "付款待确认";
                                }else if(record.getString("payStatusCode").equals("PARTPAYMENT")) {
                                    payStatus = "部分付款";
                                }else if(record.getString("payStatusCode").equals("FINISHPAYMENT")) {
                                    payStatus = "付款完成";
                                }
                                xsht.setPayStatus(payStatus);
                            }
                            if(record.getString("statusCode")!=null) {
                                String statusCode = "";
                                if(record.getString("statusCode").equals("DELIVERGOODS")&&record.getString("nextStatus").equals("DELIVERY_TAKE_PART")) {
                                    statusCode = "部分发货待收款";
                                }else if(record.getString("statusCode").equals("ENDORDER")&&record.getString("nextStatus").equals("ENDORDER")) {
                                    statusCode = "已完成";
                                }else if(record.getString("statusCode").equals("CONFIRMORDER")&&record.getString("nextStatus").equals("DELIVERGOODS")) {
                                    statusCode = "待发货";
                                }else if(record.getString("statusCode").equals("DELIVERGOODS")&&record.getString("nextStatus").equals("TAKEDELIVERY")) {
                                    statusCode = "待收货";
                                }
                                xsht.setOrderStatus(statusCode);
                            }
                            xshtService.insertSysYongyouXsht(xsht);
                        }
                    }
                }
            }
        }
        return recordCount;
    }

    @Override
    public int asyncXsfp(TimeStrVo vo){
        String apiUrl = "/yonbip/sd/vouchersaleinvoice/list";
        String accessUrl = getApiUrl(apiUrl);
        HashMap param = new HashMap();
        param.put("pageIndex", 1);
        param.put("pageSize", 500);
        List<HashMap<String,Object>> fieldsList = new ArrayList<>();
        HashMap fields = new HashMap();
        fields.put("field", "vouchdate");
//        fields.put("op", "between");
//        fields.put("value1", vo.getAsyncTimeStart());
//        fields.put("value2", vo.getAsyncTimeEnd());
        fields.put("op", "like");
        fields.put("value1", vo.getAsyncTimeStart());
        fieldsList.add(fields);
        param.put("simpleVOs", fieldsList);
        String result = null;
        try {
            result = RequestUtil.doPost(accessUrl, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject res = JSONObject.parseObject(result);
        JSONObject data = JSONObject.parseObject(res.getString("data"));
        int pageCount = data.getInteger("pageCount");
        int recordCount = data.getInteger("recordCount");
        logger.info("------recordCount-----" + recordCount);
        logger.info("------pageCount-----" + pageCount);

        if(pageCount>0) {
            xsfpService.deleteByDateRange(vo.getAsyncTimeStart());
            for (int i = 1; i <= pageCount; i++) {
                Map sub = new LinkedHashMap<>();
                sub.put("pageIndex", i);
                sub.put("pageSize", 500);
                List<HashMap<String,Object>> SubFieldsList = new ArrayList<>();
                HashMap subFields = new HashMap();
                subFields.put("field", "vouchdate");
//                subFields.put("op", "between");
//                subFields.put("value1", vo.getAsyncTimeStart());
//                subFields.put("value2", vo.getAsyncTimeEnd());
                subFields.put("op", "like");
                subFields.put("value1", vo.getAsyncTimeStart());
                SubFieldsList.add(fields);
                sub.put("simpleVOs", SubFieldsList);
                String subResult = null;
                try {
                    subResult = RequestUtil.doPost(accessUrl, sub);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                JSONObject subRes = JSONObject.parseObject(subResult);
                JSONObject subData = JSONObject.parseObject(subRes.getString("data"));
                JSONArray recordList = subData.getJSONArray("recordList");
                if (recordList.size() > 0) {
                    for (int index = 0; index < recordList.size(); index++) {
                        JSONObject record = recordList.getJSONObject(index);
                        SysYongyouXsfp xsfp = new SysYongyouXsfp();
                        xsfp.setOrgname(record.getString("orgName"));
                        xsfp.setCode(record.getString("code"));
                        xsfp.setTransactiontypeidName(record.getString("transactionTypeId_name"));
                        xsfp.setVouchdate(record.getString("vouchdate"));
                        xsfp.setAuditdate(record.getString("auditDate"));
                        xsfp.setStatus(record.getString("status"));
                        xsfp.setAgentname(record.getString("agentName"));
                        xsfp.setInvagentname(record.getString("invAgentName"));
                        xsfp.setCurrencyCode(record.getString("currency_code"));
                        xsfp.setNatcurrencyName(record.getString("natCurrency_name"));
                        xsfp.setInvdirection(record.getString("invDirection"));
                        xsfp.setBdinvoicetypename(record.getString("bdInvoiceTypeName"));
                        xsfp.setSaleinvoicedetailsSaleorgidName(record.getString("saleInvoiceDetails_saleOrgId_name"));
                        xsfp.setSrcvouchercolumnno(record.getString("srcVoucherColumnNo"));
                        xsfp.setAgentproductcode(record.getString("agentProductCode"));
                        xsfp.setAgentproductname(record.getString("agentProductName"));
                        xsfp.setAgentskucode(record.getString("agentSkuCode"));
                        xsfp.setAgentskuname(record.getString("agentSkuName"));
                        xsfp.setProductcode(record.getString("productCode"));
                        xsfp.setProductname(record.getString("productName"));
                        xsfp.setSpecides(record.getString("speciDes"));
                        xsfp.setCusproductcode(record.getString("cusProductCode"));
                        xsfp.setCusproductname(record.getString("cusProductName"));
                        xsfp.setCusproductversion(record.getString("cusProductVersion"));
                        xsfp.setInvproducttype(record.getString("invProductType"));
                        xsfp.setChargeunitname(record.getString("chargeUnitName"));
                        xsfp.setQty(record.getString("qty"));
                        xsfp.setOritaxunitprice(record.getString("oriTaxUnitPrice"));
                        xsfp.setTaxrate(record.getString("taxRate"));
                        xsfp.setNattaxunitprice(record.getString("natTaxUnitPrice"));
                        xsfp.setNatunitprice(record.getString("natUnitPrice"));
                        xsfp.setColumnno(record.getString("columnNo"));
                        xsfp.setSaleinvoicedetailsSaledeptname(record.getString("saleInvoiceDetails_saleDeptName"));
                        xsfp.setSaleinvoicedetailsSaleusername(record.getString("saleInvoiceDetails_saleUserName"));
                        xsfp.setAccorigreceivemoney(record.getString("accOrigReceiveMoney"));
                        xsfp.setNataccreceivemoney(record.getString("natAccReceiveMoney"));
                        xsfp.setCurrentAuditor(record.getString("current_auditor"));
                        xsfp.setSaleinvoicedetailsModel(record.getString("saleInvoiceDetails_model"));
                        xsfp.setSaleinvoicedetailsMemo(record.getString("saleInvoiceDetails_memo"));
                        xsfp.setVoucherSaleinvoicelistUserdefine001(record.getString("voucher_saleinvoicelist_userDefine001"));
                        JSONObject saleInvoiceDetails = record.getJSONObject("saleInvoiceDetails");
                        if(saleInvoiceDetails!=null) {
                            if (saleInvoiceDetails.getString("natSum") != null) {
                                xsfp.setSaleinvoicedetailsnatsum(saleInvoiceDetails.getString("natSum"));
                            }
                            if (saleInvoiceDetails.getString("natMoney") != null) {
                                xsfp.setSaleinvoicedetailsnatmoney(saleInvoiceDetails.getString("natMoney"));
                            }
                            if (saleInvoiceDetails.getString("natTax") != null) {
                                xsfp.setSaleinvoicedetailsnattax(saleInvoiceDetails.getString("natTax"));
                            }
                            if (saleInvoiceDetails.getString("natSum") != null) {
                                xsfp.setSaleinvoicedetailsorisum(saleInvoiceDetails.getString("natSum"));
                            }
                            if (saleInvoiceDetails.getString("oriTax") != null) {
                                xsfp.setSaleinvoicedetailsoritax(saleInvoiceDetails.getString("oriTax"));
                            }
                        }
                        xsfpService.insertSysYongyouXsfp(xsfp);
                    }
                }
            }
        }

        return recordCount;
    }

    @Override
    public int asyncXsck(TimeStrVo vo){
        String apiUrl = "/yonbip/scm/salesout/list";
        String accessUrl = getApiUrl(apiUrl);
        HashMap param = new HashMap();
        param.put("pageIndex", 1);
        param.put("pageSize", 500);
        List<HashMap<String,Object>> fieldsList = new ArrayList<>();
        HashMap fields = new HashMap();
        fields.put("field", "vouchdate");
//        fields.put("op", "between");
//        fields.put("value1", vo.getAsyncTimeStart());
//        fields.put("value2", vo.getAsyncTimeEnd());
        fields.put("op", "like");
        fields.put("value1", vo.getAsyncTimeStart());
        fieldsList.add(fields);
        param.put("simpleVOs", fieldsList);
        String result = null;
        try {
            result = RequestUtil.doPost(accessUrl, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject res = JSONObject.parseObject(result);
        JSONObject data = JSONObject.parseObject(res.getString("data"));
        int pageCount = data.getInteger("pageCount");
        int recordCount = data.getInteger("recordCount");
        logger.info("------recordCount-----" + recordCount);
        logger.info("------pageCount-----" + pageCount);
        if(pageCount>0) {
            xsckService.deleteByDateRange(vo.getAsyncTimeStart());
            for (int i = 1; i <= pageCount; i++) {
                Map sub = new LinkedHashMap<>();
                sub.put("pageIndex", i);
                sub.put("pageSize", 500);
                List<HashMap<String,Object>> SubFieldsList = new ArrayList<>();
                HashMap subFields = new HashMap();
                subFields.put("field", "vouchdate");
//                subFields.put("op", "between");
//                subFields.put("value1", vo.getAsyncTimeStart());
//                subFields.put("value2", vo.getAsyncTimeEnd());
                subFields.put("op", "like");
                subFields.put("value1", vo.getAsyncTimeStart());
                SubFieldsList.add(fields);
                sub.put("simpleVOs", SubFieldsList);
                String subResult = null;
                try {
                    subResult = RequestUtil.doPost(accessUrl, sub);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                JSONObject subRes = JSONObject.parseObject(subResult);
                JSONObject subData = JSONObject.parseObject(subRes.getString("data"));
                JSONArray recordList = subData.getJSONArray("recordList");
                if (recordList.size() > 0) {
                    for (int index = 0; index < recordList.size(); index++) {
                        JSONObject record = recordList.getJSONObject(index);
                        SysYongyouXsck xsck = new SysYongyouXsck();
                        xsck.setVouchdate(record.getString("vouchdate"));
                        xsck.setCode(record.getString("code"));
                        xsck.setBustypeName(record.getString("bustype_name"));
                        xsck.setStockinouttype(record.getString("stockInOutType"));
                        xsck.setCustName(record.getString("cust_name"));
                        xsck.setDepartmentName(record.getString("department_name"));
                        xsck.setOperatorName(record.getString("operator_name"));
                        xsck.setWarehouseName(record.getString("warehouse_name"));
                        xsck.setOrgName(record.getString("org_name"));
                        xsck.setInventoryownerName(record.getString("inventoryowner_name"));
                        xsck.setOwnertype(record.getString("ownertype"));
                        xsck.setSalesorgName(record.getString("salesOrg_name"));
                        xsck.setAccountorgName(record.getString("accountOrg_name"));
                        xsck.setInvoiceorgName(record.getString("invoiceOrg_name"));
                        xsck.setStockmgrName(record.getString("stockMgr_name"));
                        xsck.setExpensenatsum(record.getString("expenseNatSum"));
                        xsck.setExpensenatmoney(record.getString("expenseNatMoney"));
                        xsck.setInvoicecustName(record.getString("invoiceCust_name"));
                        xsck.setContactname(record.getString("contactName"));
                        xsck.setCarryoverofcostmethod(record.getString("carryOverOfCostMethod"));
                        xsck.setStatus(record.getString("status"));
                        xsck.setAudittime(record.getString("auditTime"));
                        xsck.setAuditdate(record.getString("auditDate"));
                        xsck.setAuditor(record.getString("auditor"));
                        xsck.setMemo(record.getString("memo"));
                        xsck.setReturncount(record.getString("returncount"));

                        JSONObject headItem = record.getJSONObject("salesOutDefineCharacter");
                        if(headItem!=null) {
                            if (headItem.getString("headDefine1") != null) {
                                xsck.setHeaditemdefine1(headItem.getString("headDefine1"));
                            }
                        }

                        xsck.setCreator(record.getString("creator"));
                        xsck.setCreatetime(record.getString("createTime"));
                        xsck.setModifier(record.getString("modifier"));
                        xsck.setModifytime(record.getString("modifyTime"));
                        xsck.setExchratedate(record.getString("exchRateDate"));
                        xsck.setRetailagentname(record.getString("retailAgentName"));
                        xsck.setModifyinvoicetype(record.getString("modifyInvoiceType"));
                        xsck.setBdinvoicetypeidName(record.getString("bdInvoiceTypeId_name"));
                        xsck.setInvoicetitletype(record.getString("invoiceTitleType"));
                        xsck.setDiliverstatus(record.getString("diliverStatus"));
                        xsck.setNatcurrencyname(record.getString("natCurrencyName"));
                        xsck.setProductCcode(record.getString("product_cCode"));
                        xsck.setProductCname(record.getString("product_cName"));
                        xsck.setProductskuCcode(record.getString("productsku_cCode"));
                        xsck.setCurrencyname(record.getString("currencyName"));
                        xsck.setProductskuCname(record.getString("productsku_cName"));
                        xsck.setPropertiesvalue(record.getString("propertiesValue"));
                        xsck.setBatchno(record.getString("batchno"));
                        xsck.setInvaliddate(record.getString("invaliddate"));
                        xsck.setQty(record.getString("qty"));
                        xsck.setUnit(record.getString("unit"));
                        xsck.setSubqty(record.getString("subQty"));
                        xsck.setOriunitprice(record.getString("oriUnitPrice"));
                        xsck.setOritaxunitprice(record.getString("oriTaxUnitPrice"));
                        xsck.setOrimoney(record.getString("oriMoney"));
                        xsck.setOrisum(record.getString("oriSum"));
                        xsck.setOritax(record.getString("oriTax"));
                        xsck.setExchratetypeName(record.getString("exchRateType_name"));
                        xsck.setTaxrate(record.getString("taxRate"));
                        xsck.setSalereturnqty(record.getString("saleReturnQty"));
                        xsck.setInvoiceqty(record.getString("invoiceQty"));
                        xsck.setExchrate(record.getString("exchRate"));
                        xsck.setSalesoutaccountingmethod(record.getString("salesoutAccountingMethod"));
                        xsck.setBizflowName(record.getString("bizFlow_name"));
                        xsck.setModeldescription(record.getString("modelDescription"));
                        xsck.setBarcode(record.getString("barCode"));
                        xsck.setContactsquantity(record.getString("contactsQuantity"));
                        xsck.setContactspieces(record.getString("contactsPieces"));
                        xsck.setPriceqty(record.getString("priceQty"));
                        xsck.setPriceuomName(record.getString("priceUOM_name"));
                        xsck.setCostunitprice(record.getString("costUnitPrice"));
                        xsck.setCostmoney(record.getString("costMoney"));
                        xsck.setNatunitprice(record.getString("natUnitPrice"));
                        xsck.setNattaxunitprice(record.getString("natTaxUnitPrice"));
                        xsck.setNatmoney(record.getString("natMoney"));
                        xsck.setNatsum(record.getString("natSum"));
                        xsck.setNattax(record.getString("natTax"));
                        xsck.setFirstupcode(record.getString("firstupcode"));
                        xsck.setPostaccountstatus(record.getString("postAccountStatus"));
                        xsckService.insertSysYongyouXsck(xsck);
                    }
                }
            }
        }
        return recordCount;
    }

    @Override
    public int asyncQtck(TimeStrVo vo){
        String apiUrl = "/yonbip/scm/othoutrecord/list";
        String accessUrl = getApiUrl(apiUrl);
        HashMap param = new HashMap();
        param.put("pageIndex", 1);
        param.put("pageSize", 500);
        List<HashMap<String,Object>> fieldsList = new ArrayList<>();
        HashMap fields = new HashMap();
        fields.put("field", "vouchdate");
//        fields.put("op", "between");
//        fields.put("value1", vo.getAsyncTimeStart());
//        fields.put("value2", vo.getAsyncTimeEnd());
        fields.put("op", "like");
        fields.put("value1", vo.getAsyncTimeStart());
        fieldsList.add(fields);
        param.put("simpleVOs", fieldsList);
        String result = null;
        try {
            result = RequestUtil.doPost(accessUrl, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject res = JSONObject.parseObject(result);
        JSONObject data = JSONObject.parseObject(res.getString("data"));
        int pageCount = data.getInteger("pageCount");
        int recordCount = data.getInteger("recordCount");
        logger.info("------recordCount-----" + recordCount);
        logger.info("------pageCount-----" + pageCount);
        if(pageCount>0) {
            qtckService.deleteByDateRange(vo.getAsyncTimeStart());
            for (int i = 1; i <= pageCount; i++) {
                Map sub = new LinkedHashMap<>();
                sub.put("pageIndex", i);
                sub.put("pageSize", 500);
                List<HashMap<String,Object>> SubFieldsList = new ArrayList<>();
                HashMap subFields = new HashMap();
                subFields.put("field", "vouchdate");
//                subFields.put("op", "between");
//                subFields.put("value1", vo.getAsyncTimeStart());
//                subFields.put("value2", vo.getAsyncTimeEnd());
                subFields.put("op", "like");
                subFields.put("value1", vo.getAsyncTimeStart());
                SubFieldsList.add(fields);
                sub.put("simpleVOs", SubFieldsList);
                String subResult = null;
                try {
                    subResult = RequestUtil.doPost(accessUrl, sub);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                JSONObject subRes = JSONObject.parseObject(subResult);
                JSONObject subData = JSONObject.parseObject(subRes.getString("data"));
                JSONArray recordList = subData.getJSONArray("recordList");
                if (recordList.size() > 0) {
                    for (int index = 0; index < recordList.size(); index++) {
                        JSONObject record = recordList.getJSONObject(index);
                        SysYongyouQtck qtck = new SysYongyouQtck();
                        qtck.setVouchdate(record.getString("vouchdate"));
                        qtck.setCode(record.getString("code"));
                        qtck.setOrgName(record.getString("org_name"));
                        qtck.setWarehouseName(record.getString("warehouse_name"));
                        qtck.setAccountorgName(record.getString("accountOrg_name"));
                        qtck.setDepartmentName(record.getString("department_name"));
                        qtck.setBustypeName(record.getString("bustype_name"));
                        qtck.setStockmgrName(record.getString("stockMgr_name"));
                        qtck.setStatus(record.getString("status"));
                        qtck.setCreator(record.getString("creator"));
                        qtck.setMemo(record.getString("memo"));
                        qtck.setLendsupplierName(record.getString("lendSupplier_name"));
                        qtck.setOthoutrecordsProductCcode(record.getString("othOutRecords_product_cCode"));
                        qtck.setOthoutrecordsProductCname(record.getString("othOutRecords_product_cName"));
                        qtck.setOthoutrecordsQty(record.getString("othOutRecords_qty"));
                        qtck.setOthoutrecordsUnitName(record.getString("othOutRecords_unit_name"));
                        qtck.setNatunitprice(record.getString("natUnitPrice"));
                        qtck.setNatmoney(record.getString("natMoney"));
                        qtck.setOthoutrecordsMemo(record.getString("othOutRecords_memo"));
                        qtck.setPostaccountstatus(record.getString("postAccountStatus"));
                        qtckService.insertSysYongyouQtck(qtck);
                    }
                }
            }
        }
        return recordCount;
    }

    @Override
    public int asyncCprk(TimeStrVo vo){
        String apiUrl = "/yonbip/scm/storeprorecord/list";
        String accessUrl = getApiUrl(apiUrl);
        HashMap param = new HashMap();
        param.put("pageIndex", 1);
        param.put("pageSize", 500);
        List<HashMap<String,Object>> fieldsList = new ArrayList<>();
        HashMap fields = new HashMap();
        fields.put("field", "vouchdate");
        fields.put("op", "like");
        fields.put("value1", vo.getAsyncTimeStart());
        fieldsList.add(fields);
        param.put("simpleVOs", fieldsList);
        String result = null;
        try {
            result = RequestUtil.doPost(accessUrl, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject res = JSONObject.parseObject(result);
        JSONObject data = JSONObject.parseObject(res.getString("data"));
        int pageCount = data.getInteger("pageCount");
        int recordCount = data.getInteger("recordCount");
        logger.info("------recordCount-----" + recordCount);
        logger.info("------pageCount-----" + pageCount);
        if(pageCount>0) {
            cprkService.deleteByDateRange(vo.getAsyncTimeStart());
            for (int i = 1; i <= pageCount; i++) {
                Map sub = new LinkedHashMap<>();
                sub.put("pageIndex", i);
                sub.put("pageSize", 500);
                List<HashMap<String,Object>> SubFieldsList = new ArrayList<>();
                HashMap subFields = new HashMap();
                subFields.put("field", "vouchdate");
                subFields.put("op", "like");
                subFields.put("value1", vo.getAsyncTimeStart());
                SubFieldsList.add(fields);
                sub.put("simpleVOs", SubFieldsList);
                String subResult = null;
                try {
                    subResult = RequestUtil.doPost(accessUrl, sub);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                JSONObject subRes = JSONObject.parseObject(subResult);
                JSONObject subData = JSONObject.parseObject(subRes.getString("data"));
                JSONArray recordList = subData.getJSONArray("recordList");
                if (recordList.size() > 0) {
                    for (int index = 0; index < recordList.size(); index++) {
                        JSONObject record = recordList.getJSONObject(index);
                        SysYongyouCprk cprk = new SysYongyouCprk();
                        cprk.setVouchdate(record.getString("vouchdate"));
                        cprk.setCode(record.getString("code"));
                        cprk.setDepartmentName(record.getString("department_name"));
                        cprk.setOrgName(record.getString("org_name"));
                        cprk.setTotalpieces(record.getString("totalPieces"));
                        cprk.setFactoryName(record.getString("factory_name"));
                        cprk.setFactoryfiorgName(record.getString("factoryFiOrg_name"));
                        cprk.setWarehouseName(record.getString("warehouse_name"));
                        cprk.setBustypeName(record.getString("bustype_name"));
                        cprk.setAccountorgName(record.getString("accountOrg_name"));
                        cprk.setMemo(record.getString("memo"));
                        cprk.setOperatorName(record.getString("operator_name"));
                        cprk.setProductCcode(record.getString("product_cCode"));
                        cprk.setProductCname(record.getString("product_cName"));
                        cprk.setProductskuCcode(record.getString("productsku_cCode"));
                        cprk.setProductskuCname(record.getString("productsku_cName"));
                        cprk.setBatchno(record.getString("batchno"));
                        cprk.setQty(record.getString("qty"));
                        cprk.setProductUnitname(record.getString("product_unitName"));
                        cprk.setSubqty(record.getString("subQty"));
                        cprk.setStockunitName(record.getString("stockUnit_name"));
                        cprk.setStockstatusdocName(record.getString("stockStatusDoc_name"));
                        cprk.setNatunitprice(record.getString("natUnitPrice"));
                        cprk.setNatmoney(record.getString("natMoney"));
                        cprk.setStatus(record.getString("status"));
                        cprk.setPostaccountstatus(record.getString("postAccountStatus"));
                        cprkService.insertSysYongyouCprk(cprk);
                    }
                }
            }
        }
        return recordCount;
    }

    @Override
    public int asyncClck(TimeStrVo vo){
        String apiUrl = "/yonbip/scm/materialout/list";
        String accessUrl = getApiUrl(apiUrl);
        HashMap param = new HashMap();
        param.put("pageIndex", 1);
        param.put("pageSize", 500);
        List<HashMap<String,Object>> fieldsList = new ArrayList<>();
        HashMap fields = new HashMap();
        fields.put("field", "vouchdate");
        fields.put("op", "like");
        fields.put("value1", vo.getAsyncTimeStart());
        fieldsList.add(fields);
        param.put("simpleVOs", fieldsList);
        String result = null;
        try {
            result = RequestUtil.doPost(accessUrl, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject res = JSONObject.parseObject(result);
        JSONObject data = JSONObject.parseObject(res.getString("data"));
        int pageCount = data.getInteger("pageCount");
        int recordCount = data.getInteger("recordCount");
        logger.info("------recordCount-----" + recordCount);
        logger.info("------pageCount-----" + pageCount);
        if(pageCount>0) {
            clckService.deleteByDateRange(vo.getAsyncTimeStart());
            for (int i = 1; i <= pageCount; i++) {
                Map sub = new LinkedHashMap<>();
                sub.put("pageIndex", i);
                sub.put("pageSize", 500);
                List<HashMap<String,Object>> SubFieldsList = new ArrayList<>();
                HashMap subFields = new HashMap();
                subFields.put("field", "vouchdate");
                subFields.put("op", "like");
                subFields.put("value1", vo.getAsyncTimeStart());
                SubFieldsList.add(fields);
                sub.put("simpleVOs", SubFieldsList);
                String subResult = null;
                try {
                    subResult = RequestUtil.doPost(accessUrl, sub);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                JSONObject subRes = JSONObject.parseObject(subResult);
                JSONObject subData = JSONObject.parseObject(subRes.getString("data"));
                JSONArray recordList = subData.getJSONArray("recordList");
                if (recordList.size() > 0) {
                    for (int index = 0; index < recordList.size(); index++) {
                        JSONObject record = recordList.getJSONObject(index);
                        SysYongyouClck clck = new SysYongyouClck();
                        clck.setVouchdate(record.getString("vouchdate"));
                        clck.setIsbeginning(record.getString("isBeginning"));
                        clck.setCode(record.getString("code"));
                        clck.setOrgName(record.getString("org_name"));
                        clck.setProductskucpCcode(record.getString("productskuCp_cCode"));
                        clck.setProductskucpCname(record.getString("productskuCp_cName"));
                        clck.setDepartmentName(record.getString("department_name"));
                        clck.setWarehouseName(record.getString("warehouse_name"));
                        clck.setAuditdate(record.getString("auditDate"));
                        clck.setStockmgrName(record.getString("stockMgr_name"));
                        clck.setMemo(record.getString("memo"));
                        clck.setAccountorgName(record.getString("accountOrg_name"));
                        clck.setContactsquantity(record.getString("contactsQuantity"));
                        clck.setUpcode(record.getString("upcode"));
                        clck.setProductCcode(record.getString("product_cCode"));
                        clck.setProductCname(record.getString("product_cName"));
                        clck.setQty(record.getString("qty"));
                        clck.setProductUnitname(record.getString("product_unitName"));
                        clck.setNatunitprice(record.getString("natUnitPrice"));
                        clck.setNatmoney(record.getString("natMoney"));
                        clck.setStatus(record.getString("status"));
                        clck.setPropertyrightstransferred(record.getString("propertyRightsTransferred"));
                        clck.setPostaccountstatus(record.getString("postAccountStatus"));
                        clck.setTopupcode(record.getString("topupcode"));
                        clckService.insertSysYongyouClck(clck);
                    }
                }
            }
        }
        return recordCount;
    }

    @Override
    public int asyncCgrk(TimeStrVo vo){
        String apiUrl = "/yonbip/scm/purinrecord/list";
        String accessUrl = getApiUrl(apiUrl);
        HashMap param = new HashMap();
        param.put("pageIndex", 1);
        param.put("pageSize", 500);
        List<HashMap<String,Object>> fieldsList = new ArrayList<>();
        HashMap fields = new HashMap();
        fields.put("field", "vouchdate");
        fields.put("op", "like");
        fields.put("value1", vo.getAsyncTimeStart());
        fieldsList.add(fields);
        param.put("simpleVOs", fieldsList);
        String result = null;
        try {
            result = RequestUtil.doPost(accessUrl, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject res = JSONObject.parseObject(result);
        JSONObject data = JSONObject.parseObject(res.getString("data"));
        int pageCount = data.getInteger("pageCount");
        int recordCount = data.getInteger("recordCount");
        logger.info("------recordCount-----" + recordCount);
        logger.info("------pageCount-----" + pageCount);
        if(pageCount>0) {
            cgrkService.deleteByDateRange(vo.getAsyncTimeStart());
            for (int i = 1; i <= pageCount; i++) {
                Map sub = new LinkedHashMap<>();
                sub.put("pageIndex", i);
                sub.put("pageSize", 500);
                List<HashMap<String,Object>> SubFieldsList = new ArrayList<>();
                HashMap subFields = new HashMap();
                subFields.put("field", "vouchdate");
                subFields.put("op", "like");
                subFields.put("value1", vo.getAsyncTimeStart());
                SubFieldsList.add(fields);
                sub.put("simpleVOs", SubFieldsList);
                String subResult = null;
                try {
                    subResult = RequestUtil.doPost(accessUrl, sub);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                JSONObject subRes = JSONObject.parseObject(subResult);
                JSONObject subData = JSONObject.parseObject(subRes.getString("data"));
                JSONArray recordList = subData.getJSONArray("recordList");
                if (recordList.size() > 0) {
                    for (int index = 0; index < recordList.size(); index++) {
                        JSONObject record = recordList.getJSONObject(index);
                        SysYongyouCgrk cgrk = new SysYongyouCgrk();
                        cgrk.setVouchdate(record.getString("vouchdate"));
                        cgrk.setCode(record.getString("code"));
                        cgrk.setBustypeName(record.getString("bustype_name"));
                        cgrk.setVendorName(record.getString("vendor_name"));
                        cgrk.setWarehouseName(record.getString("warehouse_name"));
                        cgrk.setPurchaseorgName(record.getString("purchaseOrg_name"));
                        cgrk.setDepartmentName(record.getString("department_name"));
                        cgrk.setAuditdate(record.getString("auditDate"));
                        cgrk.setProductCcode(record.getString("product_cCode"));
                        cgrk.setProductCname(record.getString("product_cName"));
                        cgrk.setQty(record.getString("qty"));
                        cgrk.setUnitName(record.getString("unit_name"));
                        cgrk.setOritaxunitprice(record.getString("oriTaxUnitPrice"));
                        cgrk.setOrisum(record.getString("oriSum"));
                        cgrk.setInstocktype(record.getString("inStockType"));
                        cgrk.setPrintcount(record.getString("printCount"));
                        cgrk.setStatus(record.getString("status"));
                        cgrk.setAuditor(record.getString("auditor"));
                        cgrk.setAudittime(record.getString("auditTime"));
                        JSONObject headItem = record.getJSONObject("purInRecordDefineCharacter");
                        if(headItem!=null) {
                            if (headItem.getString("headDefine1") != null) {
                                cgrk.setHeaditemdefine1(headItem.getString("headDefine1"));
                            }
                        }
                        cgrk.setSupplierproductcode(record.getString("supplierProductCode"));
                        cgrk.setSupplierproductname(record.getString("supplierProductName"));
                        cgrk.setReverseinvoiceqty(record.getString("reverseInvoiceQty"));
                        cgrk.setFirstupcode(record.getString("firstupcode"));
                        cgrk.setPostaccountstatus(record.getString("postAccountStatus"));
                        cgrk.setPurinrecordsId(record.getString("purInRecords_id"));
                        cgrk.setBatchno(record.getString("batchno"));
                        cgrkService.insertSysYongyouCgrk(cgrk);
                    }
                }
            }
        }
        return recordCount;
    }

    @Override
    public int asyncCgfp(TimeStrVo vo){
        String apiUrl = "/yonbip/scm/purinvoice/list";
        String accessUrl = getApiUrl(apiUrl);
        HashMap param = new HashMap();
        param.put("pageIndex", 1);
        param.put("pageSize", 500);
        List<HashMap<String,Object>> fieldsList = new ArrayList<>();
        HashMap fields = new HashMap();
        fields.put("field", "vouchdate");
        fields.put("op", "like");
        fields.put("value1", vo.getAsyncTimeStart());
        fieldsList.add(fields);
        param.put("simpleVOs", fieldsList);
        String result = null;
        try {
            result = RequestUtil.doPost(accessUrl, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject res = JSONObject.parseObject(result);
        JSONObject data = JSONObject.parseObject(res.getString("data"));
        int pageCount = data.getInteger("pageCount");
        int recordCount = data.getInteger("recordCount");

        if(pageCount>0) {
            cgfpService.deleteYongyouCgfpByDateRange(vo.getAsyncTimeStart());
            for (int i = 1; i <= pageCount; i++) {
                Map sub = new LinkedHashMap<>();
                sub.put("pageIndex", i);
                sub.put("pageSize", 500);
                List<HashMap<String,Object>> SubFieldsList = new ArrayList<>();
                HashMap subFields = new HashMap();
                subFields.put("field", "vouchdate");
                subFields.put("op", "like");
                subFields.put("value1", vo.getAsyncTimeStart());
                SubFieldsList.add(fields);
                sub.put("simpleVOs", SubFieldsList);
                String subResult = null;
                try {
                    subResult = RequestUtil.doPost(accessUrl, sub);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                JSONObject subRes = JSONObject.parseObject(subResult);
                JSONObject subData = JSONObject.parseObject(subRes.getString("data"));
                JSONArray recordList = subData.getJSONArray("recordList");
                if (recordList.size() > 0) {
                    for (int index = 0; index < recordList.size(); index++) {
                        JSONObject record = recordList.getJSONObject(index);
                        SysYongyouCgfp cgfp = new SysYongyouCgfp();
                        cgfp.setVouchdate(record.getString("vouchdate"));
                        cgfp.setCode(record.getString("code"));
                        cgfp.setOrgName(record.getString("org_name"));
                        cgfp.setIninvoiceorgName(record.getString("inInvoiceOrg_name"));
                        cgfp.setBustypeName(record.getString("bustype_name"));
                        cgfp.setVendorName(record.getString("vendor_name"));
                        cgfp.setProductCcode(record.getString("product_cCode"));
                        cgfp.setStatus(record.getString("status"));
                        cgfp.setProductCname(record.getString("product_cName"));
                        cgfp.setQty(record.getString("qty"));
                        cgfp.setUnitName(record.getString("unit_Name"));
                        cgfp.setOritaxunitprice(record.getString("oriTaxUnitPrice"));
                        cgfp.setListorisum(record.getString("listOriSum"));
                        cgfp.setBalancedate(record.getString("balanceDate"));
                        cgfp.setMemo(record.getString("memo"));
                        cgfp.setPurinvoicesFirstupcode(record.getString("purinvoices_firstupcode"));
                        cgfp.setUpcode(record.getString("upcode"));
                        cgfpService.insertSysYongyouCgfp(cgfp);
                    }
                }
            }
        }
        return recordCount;
    }

    @Override
    public int asyncCgdd(TimeStrVo vo){
        String apiUrl = "/yonbip/scm/purchaseorder/list";
        String accessUrl = getApiUrl(apiUrl);
        HashMap param = new HashMap();
        param.put("pageIndex", 1);
        param.put("pageSize", 500);
        List<HashMap<String,Object>> fieldsList = new ArrayList<>();
        HashMap fields = new HashMap();
        fields.put("field", "vouchdate");
        fields.put("op", "like");
        fields.put("value1", vo.getAsyncTimeStart());
        fieldsList.add(fields);
        param.put("simpleVOs", fieldsList);
        String result = null;
        try {
            result = RequestUtil.doPost(accessUrl,param);
        }catch (IOException e){
            e.printStackTrace();
        }
        JSONObject res = JSONObject.parseObject(result);
        JSONObject data = JSONObject.parseObject(res.getString("data"));
        int pageCount = data.getInteger("pageCount");
        int recordCount = data.getInteger("recordCount");
        logger.info("----pageCount----"+pageCount);
        logger.info("----recordCount----"+recordCount);
        if(pageCount>0) {
            cgddService.deleteYongyouCgddByDate(vo.getAsyncTimeStart());
            for (int i = 1; i <= pageCount; i++) {
                Map sub = new LinkedHashMap<>();
                sub.put("pageIndex", i);
                sub.put("pageSize", 500);
                List<HashMap<String,Object>> SubFieldsList = new ArrayList<>();
                HashMap subFields = new HashMap();
                subFields.put("field", "vouchdate");
                subFields.put("op", "like");
                subFields.put("value1", vo.getAsyncTimeStart());
                SubFieldsList.add(subFields);
                sub.put("simpleVOs", SubFieldsList);
                String subResult = null;
                try {
                    subResult = RequestUtil.doPost(accessUrl, sub);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                JSONObject subRes = JSONObject.parseObject(subResult);
                JSONObject subData = JSONObject.parseObject(subRes.getString("data"));
                JSONArray recordList = subData.getJSONArray("recordList");
                if (recordList.size() > 0) {
                    for (int index = 0; index < recordList.size(); index++) {
                        JSONObject record = recordList.getJSONObject(index);
                        SysYongyouCgdd cgdd = new SysYongyouCgdd();
                        cgdd.setVouchdate(record.getString("vouchdate"));
                        cgdd.setCode(record.getString("code"));
                        cgdd.setOrgName(record.getString("org_name"));
                        cgdd.setVendorName(record.getString("vendor_name"));
                        cgdd.setOperatorName(record.getString("operator_name"));
                        cgdd.setStatus(record.getString("status"));
                        cgdd.setCreator(record.getString("creator"));
                        cgdd.setMemo(record.getString("memo"));
                        cgdd.setProductCcode(record.getString("product_cCode"));
                        cgdd.setProductCname(record.getString("product_cName"));
                        cgdd.setUnitName(record.getString("unit_name"));
                        cgdd.setQty(record.getString("qty"));
                        cgdd.setAmountpayable(record.getString("amountPayable"));
                        JSONObject headFreeItem = record.getJSONObject("headFreeItem");
                        cgdd.setHeadfreeitemdefine1Name(headFreeItem.getString("define1_name"));
                        JSONObject bodyFreeItem = record.getJSONObject("bodyFreeItem");
                        cgdd.setBodyfreeitemdefine1(bodyFreeItem.getString("define1"));
                        cgdd.setBodyfreeitemdefine2(bodyFreeItem.getString("define2"));
                        JSONObject orderCharacter = record.getJSONObject("purchaseOrderDefineCharacter");
                        if(orderCharacter!=null) {
                            if(orderCharacter.getString("headDefine1")!=null) {
                                cgdd.setHeaditemdefine1(orderCharacter.getString("headDefine1"));
                            }
                            if(orderCharacter.getString("sxf")!=null) {
                                cgdd.setSxf(orderCharacter.getString("sxf"));
                            }
                            if(orderCharacter.getString("yclfy")!=null) {
                                cgdd.setYclfy(orderCharacter.getString("yclfy"));
                            }
                            if(orderCharacter.getString("attrext9")!=null) {
                                cgdd.setAttrext9Yunfei(orderCharacter.getString("attrext9"));
                            }
                            if(orderCharacter.getString("attrext8")!=null) {
                                cgdd.setAttrext8Dlf(orderCharacter.getString("attrext8"));
                            }
                            if(orderCharacter.getString("attrext10")!=null) {
                                cgdd.setAttrext10Zx(orderCharacter.getString("attrext10"));
                            }
                            if(orderCharacter.getString("attrext7")!=null) {
                                cgdd.setAttrext7Hl(orderCharacter.getString("attrext7"));
                            }
                        }
                        JSONObject ordersCharacter = record.getJSONObject("purchaseOrdersDefineCharacter");
                        if (ordersCharacter != null) {
                            if(ordersCharacter.getString("WBDJ")!=null) {
                                cgdd.setWbdj(ordersCharacter.getString("WBDJ"));
                            }
                        }
                        cgddService.insertSysYongyouCgdd(cgdd);
                    }
                }
            }
        }
        return recordCount;
    }

    public static String getApiUrl(String url) {
        String tenantResult = getTokenUrl();
        JSONObject jsonObject = JSONObject.parseObject(tenantResult);
        String gatewayUrl = jsonObject.getJSONObject("data").getString("gatewayUrl");
        String tokenUrl = jsonObject.getJSONObject("data").getString("tokenUrl");
        String accessToken = getAccessToken(tokenUrl);
        return gatewayUrl+url+"?access_token=" + accessToken;
    }

    public static String getAccessToken(String tokenUrl) {
        long timestamp = System.currentTimeMillis();
        String source = "appKey" + appKey + "timestamp" + timestamp;
        Mac mac = null;
        try {
            mac = Mac.getInstance("HmacSHA256");
        }catch (NoSuchAlgorithmException e){
            e.printStackTrace();
        }
        SecretKeySpec secretKey = new SecretKeySpec(appSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        try {
            mac.init(secretKey);
        }catch (InvalidKeyException e){
            e.printStackTrace();
        }
        byte[] bytes = mac.doFinal(source.getBytes(StandardCharsets.UTF_8));
        String hash = Base64.getEncoder().encodeToString(bytes);
        String signature1 = null;
        try {
            signature1 = URLEncoder.encode(hash, StandardCharsets.UTF_8.name());
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        String getTokenUrl = tokenUrl + "/open-auth/selfAppAuth/getAccessToken?appKey=" + appKey + "&timestamp=" + timestamp + "&signature=" + signature1;
        String tokenResult = null;
        try {
            tokenResult = RequestUtil.doGet(getTokenUrl);
        }catch (IOException e){
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(tokenResult);
        String accessToken = jsonObject.getJSONObject("data").getString("access_token");
        return accessToken;
    }

    public static  String getSignature(Map<String, String> params, String appSecret) {
        String source = buildSource(params);
        byte[] bytes;
        try {
            Mac mac = Mac.getInstance(ALGORITHM);
            SecretKeySpec secretKey = new SecretKeySpec(appSecret.getBytes(StandardCharsets.UTF_8), ALGORITHM);
            mac.init(secretKey);
            bytes = mac.doFinal(source.getBytes(StandardCharsets.UTF_8));
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new BusinessException("exception when do open api token request signature", e);
        }
        String hash = Base64.getEncoder().encodeToString(bytes);
        try {
            return URLEncoder.encode(hash, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            throw new BusinessException("implementation error, utf-8 not found, What year is it?");
        }
    }

    private static String buildSource(Map<String, String> params) {
        Map<String, String> treeMap;
        if (params instanceof TreeMap) {
            treeMap = params;
        } else {
            treeMap = new TreeMap<>(params);
        }
        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, String> entry : treeMap.entrySet()) {
            builder.append(entry.getKey()).append(entry.getValue());
        }
        return builder.toString();
    }

    public static String getTokenUrl(){
        String tenantUrl = "https://apigateway.yonyoucloud.com/open-auth/dataCenter/getGatewayAddress?tenantId=" + tenantId;
        String tenantResult = null;
        try {
            tenantResult = RequestUtil.doGet(tenantUrl);
        }catch (IOException e){
            e.printStackTrace();
        }
        return tenantResult;
    }

    public String getNearWeekDate(int num){
        // 创建Calendar对象
        Calendar calendar = Calendar.getInstance();
        // 设置日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        calendar.add(Calendar.DAY_OF_YEAR, num);
        String pastDay = sdf.format(calendar.getTime());
        return pastDay;
    }
}
